using System;
using System.Collections.Generic;
using System.Text;

namespace ThinkJot.Core.Utils
{
    //FREAKY QUICK HAXOR!
    //I dont trust this one bit.
    public static class DateTimeUtility
    {
        public static string GetUtcOffsetString(TimeSpan timeSpan)
        {
            //TimeSpan timeSpan = new TimeSpan(ticks);

            int hours = (int)timeSpan.TotalHours;
            int minutes = (int)(timeSpan.TotalMinutes - (hours * 60));

            if (timeSpan.Ticks >= 0)
            {
                return "+" + GetPaddedtimeString(hours) + ":" + GetPaddedtimeString(minutes);
            }
            else
            {
                return "-" + GetPaddedtimeString(hours * -1) + ":" + GetPaddedtimeString(minutes * -1);
            }
        }

        private static string GetPaddedtimeString(int units)
        {
            if (units < 10) return "0" + units;
            else return units.ToString();
        }

        //offset as (+/-)hh:mm eg: +05:30 for India
        //Remember remember, we aren't validaing anything here.
        //Dear blog config manipulator, what you throw is what you catch.
        public static DateTime AddTimeOffset(DateTime srcTime, string offset)
        {
            int hours = Convert.ToInt32(offset.Substring(1, 2));
            int minutes = Convert.ToInt32(offset.Substring(4, 2));
            bool positive = offset.StartsWith("+") ? true : false;
            if (!positive)
            {
                hours = -1 * hours;
                minutes = -1 * minutes;
            }
            return srcTime.AddHours(hours).AddMinutes(minutes);
        }

        //Does the opposite of AddTimeOffset
        //if (positive) instead of if (!positive)
        public static DateTime SubtractTimeOffset(DateTime srcTime, string offset)
        {
            int hours = Convert.ToInt32(offset.Substring(1, 2));
            int minutes = Convert.ToInt32(offset.Substring(4, 2));
            bool positive = offset.StartsWith("+") ? true : false;
            if (positive)
            {
                hours = -1 * hours;
                minutes = -1 * minutes;
            }
            return srcTime.AddHours(hours).AddMinutes(minutes);
        }

        public static DateTime GetDateFromShortDateString(string strDate)
        {
            DateTime dt;
            if (!string.IsNullOrEmpty(strDate))
            {
                bool isTimeValid = DateTime.TryParse(strDate, out dt);
                if (isTimeValid)
                    return dt;
            }
            return DateTime.Now.ToUniversalTime();
        }
    }
}
